package smartcode.privacy;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.aliang.auto.R;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;


/**
 * @author lcj
 * 调用AgentWeb支持微信支付宝跳转
 * @date 2017/12/29 15:12
 * https://github.com/Justson/AgentWeb
 */

public class WebViewActivity extends BaseActivity {
    TextView tvTitle;
    private AgentWeb mAgentWeb;
    private BaseWebViewData mData;
    private ProgressBar progressBar;
    private FrameLayout layoutAgent;
    private LinearLayout vLoading;
    //阳光保险支付H5页面
    private String loadSunshinePayUrl;

    @Override
    public int intiLayout() {
        return R.layout.activity_web_agent;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        tvTitle = findViewById(R.id.tv_title);
        if (getIntentData() != null) {
            mData = (BaseWebViewData) getIntentData();
        } else {
            showToast("地址有误", 2);
            finish();
        }
        progressBar = findViewById(R.id.progressBar);
        layoutAgent = findViewById(R.id.content_frame);
        vLoading = findViewById(R.id.layout_load);

        String title = mData.title;
        if (title != null && !title.isEmpty()) {
            tvTitle.setText(title);
        }
//        tvTitleTitle.getPaint().setFakeBoldText(true);
        initWeb();
    }

    public void initWeb() {
        String url = mData.content;
        if (TextUtils.isEmpty(url)) {
            showToast("地址有误", 2);
            finish();
            return;
        }
//        if (url.startsWith("http")) {
        vLoading.setVisibility(View.VISIBLE);
        int layoutPa = ViewGroup.LayoutParams.MATCH_PARENT;
        AgentWebConfig.debug();
        final AgentWeb.PreAgentWeb agentWeb = AgentWeb.with((Activity) this)//这里需要把 Activity 、 和 Fragment  同时传入
                .setAgentWebParent(layoutAgent, new LinearLayout.LayoutParams(layoutPa, -1))// 设置 AgentWeb 的父控件 ， 这里的view 是 LinearLayout ， 那么需要传入 LinearLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条\
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setWebViewClient(new com.just.agentweb.WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        view.loadUrl(url);
                        return true;
                    }

                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                        return super.shouldOverrideUrlLoading(view, request);
                    }

                    @Override
                    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                        super.onReceivedError(view, request, error);
                    }
                })
//                                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //注意这里开启 strict 模式 ， 设备低于 4.2 情况下回把注入的 Js 全部清空掉 ， 这里推荐使用 onJsPrompt 通信
                .createAgentWeb().ready();//
        agentWeb.go(url);


//        AgentWeb.PreAgentWeb preAgentWeb = AgentWeb.with(this)//传入Activity
//                .setAgentWebParent(layoutAgent, new LinearLayout.LayoutParams(layoutPa, -1))
//                .useDefaultIndicator()
////                    .setWebChromeClient(mWebChromeClient)
//                .setWebViewClient(mWebViewClient)
////                    .setSecutityType(AgentWeb.SecurityType.strict)
////                    .defaultProgressBarColor()
////                    .setReceivedTitleCallback(mCallback)
//                .createAgentWeb().ready();
//        mAgentWeb = preAgentWeb.go(url);
//        mAgentWeb.getAgentWebSettings().getWebSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
//        mAgentWeb.getAgentWebSettings().getWebSettings().setLoadWithOverviewMode(true);
//        mAgentWeb.getAgentWebSettings().getWebSettings().setSupportZoom(true);
//        mAgentWeb.getAgentWebSettings().getWebSettings().setBuiltInZoomControls(true);
//        if (mData.largeSize) {
//            mAgentWeb.getAgentWebSettings().getWebSettings().setTextSize(WebSettings.TextSize.LARGEST);
//        }

//        } else {
//            DyToast.getInstance().error("地址有误");
//        }
    }

    @Override
    public void onBackPressed() {
        if (mAgentWeb != null && mAgentWeb.back()) {
            //返回上一页面
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onResume() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
        super.onDestroy();
    }

    // 绘制HTML
    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=0.5, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (mAgentWeb != null) {
////            mAgentWeb.getUrlLoader(requestCode, resultCode, data);
//        }
    }


    @Override
    public void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return shouldOverrideUrlLoading(view, request.getUrl() + "");
        }

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            showLog("shouldOverrideUrlLoading:" + url);
            if (TextUtils.indexOf(url, "paymentinterface/recallWechatH5?bussinessNoWechatH5") > 0) {
                loadSunshinePayUrl = url;
            }
//            pinduoduo://com.xunmeng.pinduoduo/duo_coupon_landing.html?goods_id=71840301139&pid=9537232_123695035&cpsSign=CC_191223_9537232_123695035_eac6a374e5939ac3ea715c2bfe15bdbb&duoduo_type=2
            if (url.contains("pinduoduo://com.xunmeng.pinduoduo")) {
                return true;
//                url=url.replace("pinduoduo://com.xunmeng.pinduoduo","https://mobile.yangkeduo.com");
//                https://mobile.yangkeduo.com/duo_coupon_landing.html
            }
            if (url.contains("/index.php/Api/Index/recharge_back/info/")) {
                WebViewActivity.this.finish();
            } else if (url.startsWith("weixin://")) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    new AlertDialog.Builder(WebViewActivity.this)
                            .setMessage("未检测到微信客户端，请安装后重试！")
                            .setPositiveButton("知道了", null).show();
                }
                showLog("shouldOverrideUrlLoading2222:" + loadSunshinePayUrl + url);
                if (!TextUtils.isEmpty(loadSunshinePayUrl)) {
                    view.loadUrl(loadSunshinePayUrl);
                }
                //1、 默认返回：return super.shouldOverrideUrlLoading(view, url);
                // 这个返回的方法会调用父类方法，也就是跳转至手机浏览器，平时写webview一般都在方法里面写 webView.loadUrl(url);
                // 然后把这个返回值改成下面的false。
                //2、返回: return true; webview处理url是根据程序来执行的。
                //3、返回: return false; webview处理url是在webview内部执行。
            } else {
                view.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.i("Info", "url:" + url + " onPageStarted  target:" + view.getUrl());
            vLoading.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            vLoading.setVisibility(View.GONE);
        }
    };
}
